import React from 'react';
import './index.scss';
import Flex from '../Flex';

export default class Popup extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShow: props.show || false
    };
  }

  onClose = () => {
    const { onClose } = this.props;
    this.setState({
      isShow: false
    }, () => {
      document.body.style.overflow = 'auto';
      onClose && onClose();
    });
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.show !== this.state.isShow) {
      this.setState({
        isShow: nextProps.show
      });
    }
  }

  stopMove = (e) => {
    e.stopPropagation();
    e.preventDefault();
    document.body.style.overflow = 'hidden';
  }

  render() {
    const { header, children, type, className, closeIcon = true } = this.props
    const { isShow = false } = this.state;
    if ( isShow === false) {
      return null;
    }
    return (
      <React.Fragment>
        <div className="erayt-mask" onClick={this.onClose} onTouchStart={this.stopMove}/>
        <div className={`erayt-popup ${type ? type : 'bottom'} ${className ? className : ''}`}>
          <Flex className="erayt-popup-header bottom-line">
            <Flex.Item column="1">
              {header}
            </Flex.Item>
            { closeIcon && <svg aria-hidden="true" className="icon close-btn" onClick={this.onClose}><use xlinkHref="#icon-close" /></svg>}
          </Flex>
          <div className="xue-popup-content">
            {children}
          </div>
        </div>
      </React.Fragment>
    );
  }
}
